<template>
  <div class="container">
    <div class="p10" style="position: relative">
      <el-button type="success" @click="addO(false)">新增一级组织</el-button>
      <el-button
        type="success"
        :disabled="!selectTreeData.id"
        @click="addO(true)"
      >
        新增子组织
      </el-button>
      <el-button type="success" :disabled="!selectTreeData.id" @click="editO">
        修改
      </el-button>
      <el-button type="danger" :disabled="!selectTreeData.id" @click="delO">
        删除
      </el-button>
    </div>
    <div class="main">
      <div class="conLeft">
        <el-tree
          ref="treeRef"
          :load="loadNode"
          lazy
          :data="tree.data"
          :props="tree.defaultProps"
          node-key="id"
          highlight-current
          default-expand-all
          @node-click="selectNode"
          :default-expanded-keys="orgIdList"
          :expand-on-click-node="false"
        >
          <template #default="{ node: any, data }">
            <span class="custom-tree-node">
              <span style="margin-left: 6px">{{ data.name }}</span>
            </span>
          </template>
        </el-tree>
      </div>
      <div class="conRight">
        <el-form
          class="form"
          :model="formData"
          label-width="100px"
          ref="ruleFormData"
          :rules="rules"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="组织名称：" prop="name">
                <el-input
                  v-model="formData.name"
                  :disabled="isShow"
                  maxlength="50"
                  style="width: 200px"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="状态：" prop="state">
                <el-select
                  v-model="formData.state"
                  :disabled="isShow"
                  style="width: 200px"
                >
                  <el-option
                    :value="item.code"
                    :label="item.name"
                    v-for="item in stateList"
                    :key="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="辖区：" prop="jurisdictionalArea">
                <el-select
                  v-model="formData.jurisdictionalArea"
                  :disabled="isShow"
                  style="width: 200px"
                >
                  <el-option
                    :value="item.code"
                    :label="item.name"
                    v-for="item in options"
                    :key="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="排序：" prop="sort">
                <el-input-number
                  :disabled="isShow"
                  v-model="formData.sort"
                  :min="1"
                  :max="999"
                  style="width: 200px"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <div v-if="!isShow" style="margin-left: 20%">
            <el-button
              class="newBtn"
              @click="submit(ruleFormData)"
              :loading="btnLoading"
              :disabled="isShow"
              type="primary"
            >
              保存
            </el-button>
            <el-button @click="closeTitle" plain :disabled="isShow">
              取消
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type Node from "element-plus/es/components/tree/src/model/node";
import {
  deleteOrg,
  saveOrg,
  selectOrgById,
  selectOrgChilds,
  selectPositionByName,
  updateOrg,
} from "@/api/user.ts";
import { selectSysDictDataParentOrChilderById } from "@/api/system.ts";

const treeRef = ref();
const btnLoading = ref<boolean>(false);
const isShow = ref<boolean>(true);
const selectTreeData = ref<any>({});
const userList = ref<any[]>([]);
const orgIdList = ref<any[]>([]);
const options = ref<any[]>([]);
const stateList = ref<any[]>([
  { code: "1", name: "启用" },
  { code: "2", name: "禁用" },
]);

const positionList = ref<any[]>([]);
const ruleFormData = ref();
const rules = reactive({
  state: [{ required: true, message: "请选择", trigger: "change" }],
  jurisdictionalArea: [{ required: true, message: "请选择", trigger: "change" }],
  name: [{ required: true, message: "请输入", trigger: "blur" }],
});
const tree = reactive({
  loading: true,
  defaultProps: {
    children: "children",
    label: "name",
  },
  data: [],
});

const formData = reactive({
  id: "",
  name: "",
  jurisdictionalArea: "",
  sysOrgManagers: [
    {
      positionId: "",
      sysUserId: "",
    },
  ],
  parentId: null,
  sort: null,
  state: null,
});
const formDataCopy = reactive({});

async function loadNode(node: Node, resolve: (data: any[]) => void) {
  tree.loading = true;
  const { data, msg, success } = await selectOrgChilds({
    parentId: node?.level ? node?.data?.id : 0,
  });
  tree.loading = false;
  if (!success) {
    ElMessage.error(msg);
    return resolve([]);
  }
  if (!node?.level && data.length > 0) {
    orgIdList.value.push(data[0].id);
  }
  return resolve(data || []);
}

//列表分页查询
async function initList() {
  tree.loading = true;
  const { data, msg, success } = await selectOrgChilds({ parentId: 0 });
  if (!success) {
    ElMessage.error(msg);
    tree.loading = false;
    return;
  }
  tree.loading = false;
  tree.data = data;
  // if (data.length > 0) {
  //   orgIdList.value.push(data[0].id);
  // }
}

//保存
async function submit(ruleFormData: any) {
  if (!ruleFormData) return;
  await ruleFormData.validate(async (valid, fields) => {
    if (valid) {
      btnLoading.value = true;
      let api = !formData.id || formData.id == "" ? saveOrg : updateOrg;
      const { msg, success } = await api(formData);
      if (!success) {
        ElMessage.error(msg);
        btnLoading.value = false;
        return;
      }
      ElMessage.success("操作成功");

      if (!formData?.parentId || !Number(formData?.parentId)) {
        await initList();
      } else {
        refreshTreeNode(true);
      }
      isShow.value = true;
      btnLoading.value = false;
    } else {
      console.log("error submit!", fields);
    }
  });
}

//新增
function addO(flag) {
  Object.keys(formData).forEach((key) => (formData[key] = null));
  isShow.value = false;
  formData.sysOrgManagers = ref<any[]>([
    {
      positionId: "",
      sysUserId: "",
    },
  ]);
  if (flag) {
    formData.parentId = selectTreeData.value?.id;
  }
  formData.sort = "1";
  formData.state = "1";
}
//编辑
async function editO() {
  if (selectTreeData.value.id) {
    isShow.value = false;
  } else {
    ElMessage.error("请选择数据进行操作");
  }
}
//删除
function delO() {
  ElMessageBox.confirm(`是否删除?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { success, msg } = await deleteOrg({}, selectTreeData.value?.id);
    if (!success) {
      ElMessage.error(msg);
      return;
    }
    Object.keys(formData).forEach((key) => (formData[key] = null));
    isShow.value = false;
    formData.sysOrgManagers = ref<any[]>([
      {
        positionId: "",
        sysUserId: "",
      },
    ]);
    ElMessage.success("操作成功");
    if (!Number(selectTreeData.value?.parentId)) {
      await initList();
      return;
    }
    refreshTreeNode(false);
    selectTreeData.value = ref({});
  });
}
async function selectNode(data) {
  isShow.value = true;
  selectTreeData.value = data;
  await getSelectOrgById(data.id);
}
async function getSelectOrgById(id) {
  const { data, success, msg } = await selectOrgById({}, id);
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  if (data) {
    data.state = data?.state.toString();
    if (!data.sysOrgManagers || data.sysOrgManagers.length == 0) {
      data.sysOrgManagers = [{ positionId: "", sysUserId: "" }];
    } else {
      userList.value = data.sysOrgManagers;
    }
  }
  Object.assign(formData, { ...data });
  Object.assign(formDataCopy, { ...data });
}
async function getPosition() {
  const { data, msg, success } = await selectPositionByName();
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  positionList.value = data;
}
function closeTitle() {
  Object.assign(formData, { ...formDataCopy });
  isShow.value = true;
}

function refreshTreeNode(type: boolean) {
  // ture 刷新子节点 | false 父节点
  const nodeId = type ? selectTreeData.value.id : selectTreeData.value.parentId;
  let node = treeRef.value.getNode(nodeId);
  if (node) {
    node.loaded = false; //告诉组件这个节点需要加载
    node.expand(); // 主动调用展开节点方法，重新查询该节点下的所有子节点
  }
}

async function getDict() {
  const { data, msg, success } = await selectSysDictDataParentOrChilderById(
    "13",
  );
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  options.value = data;
}
onMounted(async () => {
  // await initList();
  await getPosition();
  await getDict();
});
</script>

<style scoped lang="scss">
@import "@/assets/styles/variable";
@import "@/assets/styles/common";
.container {
  height: $router-component-contain-height;
  display: flex;
  flex-direction: column;
}
.main {
  display: flex;
  margin-top: 10px;
  .conLeft {
    width: 340px;
    height: calc($router-component-contain-height - 60px);
  }
  .conRight {
    width: calc(100% - 350px);
    height: 100%;
    position: relative;

    .form {
      padding: 10px;
    }
  }
}
</style>
